import $util from "@/utils/index.js"
import $api from "@/api/index.js"
export default {
	state: {
		pageActiveHome: false,
		pageActiveShop: false,
		pageActiveMine: false,
		autograph: '',
		userInfo: '',
		appLogin: '',
		loginType: '',
		loginPage: '',
		isShowLogin: true,
		push_id: '',
		commonOptions: {},
		location: {},
		isShowAuth: true,
		mineInfo: {}
	},
	mutations: {
		//更新内容
		async updateUserItem(state, item) {
			let {
				key,
				val
			} = item
			if (key == 'userInfo') {
				let {
					phone = ''
				} = val
				if (phone) {
					val.split_phone = phone.substring(0, 3) + '****' + phone.substring(7, 11)
				}
			}
			state[key] = val
			if (['autograph', 'userInfo', 'appLogin', 'loginType', 'push_id'].includes(key)) {
				uni.setStorageSync(key, val)
			}
		}
	},
	actions: {
		//获取个人信息
		async getUserInfo({
			commit,
			state
		}, param) {
			let data = await $api.user.userInfo()
			commit('updateUserItem', {
				key: 'userInfo',
				val: data
			})
		},
		//获取用户个人中心数据
		async getMineInfo({
			commit,
			state
		}, param) {
			let data = await $api.mine.index()
			let {
				farmer_status = -1,
					is_landlord = 0
			} = data
			data.id = data.id || -1
			data.is_user = (farmer_status == 2 || farmer_status == 3 || is_landlord) ? 0 : 1
			commit('updateUserItem', {
				key: 'mineInfo',
				val: data
			})
		},
		// 获取用户信息
		async getAuthUserProfile({
			commit,
			state
		}, param) {
			let {
				nickName,
				avatarUrl
			} = param
			let params = $util.pick(param, ['nickName', 'avatarUrl', 'city', 'country', 'gender', 'province'])
			await $api.user.userUpdate(params)
			let data = Object.assign(state.userInfo, {
				nickName,
				avatarUrl
			})
			commit('updateUserItem', {
				key: 'userInfo',
				val: data
			})
		},
		// 获取手机号
		async getAuthPhone({
			commit,
			state
		}, {
			e = {
				detail: {}
			},
			must = false
		} = {}) {
			let {
				encryptedData = '', iv = ''
			} = e.detail;
			let phone = ''
			if (encryptedData && iv) {
				let phone = await $api.user.reportPhone({
					encryptedData,
					iv
				})
				let data = Object.assign(state.userInfo, {
					phone
				})
				commit('updateUserItem', {
					key: 'userInfo',
					val: data
				})
				return phone;
			}
		},
		// 更新公共参数
		async updateCommonOptions({
			commit,
			state
		}, param) {
			let target = {}
			if (param.scene) {
				let res = await $api.base.getWxCodeData({
					code_id: param.scene
				})
				target = Object.assign({}, state.commonOptions, res.data)
			} else {
				target = Object.assign({}, state.commonOptions, param)
			}
			let data = $util.pick(target, ['id', 'record_id'])
			commit('updateUserItem', {
				key: 'commonOptions',
				val: data
			})
			console.log(target, "======target");
			return target
		}
	}
}
